<script setup lang="ts">
import PageContainer from '@/components/PageContainer.vue';
import { ref, onMounted, computed, nextTick } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Edit, Delete, Picture } from '@element-plus/icons-vue';

// 使用已安装的 Vue Quill 富文本编辑器
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';

// API
import { artGetDetailService } from '@/api/article';
import { getChapterList, addChapter, editChapter, deleteChapter } from '@/api/detail';

const route = useRoute();
const novelId = route.params.id as string;

interface NovelInfo {
  id: string;
  title: string;
  cover: string;
  content: string;
  cate_name: string;
  state: string;
  pub_date: string;
  word_count?: number, // 新增
  chapter_count?: number, // 新增
  last_update?: Date // 新增
}

interface ChapterItem {
  id: string;
  novelId: string;
  chapterNum: number;
  title: string;
  status: string;
  content: string;
  pub_date: string;
  word_count?: number,
  read_time?: number
}

interface ApiResponse<T = any> {
  data: {
    code: string;
    msg: string;
    data: T;
  }
}

interface ChapterListResponse {
  list: ChapterItem[];
  total?: number;
  pageSize?: number;
  pageNum?: number;
}

interface ChapterForm extends Omit<ChapterItem, 'id' | 'createTime' | 'updateTime'> {
  id?: string; // 编辑时存在
}

// 响应式数据
const novelInfo = ref<NovelInfo>({
  id: '',
  title: '',
  cover: '',
  content: '',
  cate_name: '',
  state: '',
  pub_date: ''
});
const chapterList = ref<ChapterItem[]>([]);
const loading = ref(false);
const chapterDialogVisible = ref(false);
const isEditing = ref(false);
const chapterForm = ref<ChapterForm>({
  novelId: novelId,
  title: '',
  chapterNum: 1,
  status: '草稿',
  content: '',
  pub_date: ''
});
const quillEditorRef = ref(null);

// 富文本编辑器配置
const editorOptions = {
  theme: 'snow',
  modules: {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      [{ 'header': [1, 2, 3, false] }],
      [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      [{ 'indent': '-1'}, { 'indent': '+1' }],
      [{ 'color': [] }, { 'background': [] }],
      [{ 'align': [] }],
      ['link', 'image'],
      ['clean']
    ]
  },
  placeholder: '请输入章节内容...'
};

// HTML转纯文本函数
const htmlToText = (html: string | undefined): string => {
  if (!html) return '';
  try {
    const doc = new DOMParser().parseFromString(html, 'text/html');
    return doc.body.textContent || '';
  } catch (error) {
    return html.replace(/<[^>]*>/g, '');
  }
};

// 截断文本
const truncateText = (text, maxLength = 120):string => {
  if (!text) return '';
  const cleanText = text.trim();
  if (cleanText.length <= maxLength) return cleanText;
  return cleanText.substring(0, maxLength) + '...';
};

// 获取纯文本简介
const plainSummary = computed(() => {
  const text = htmlToText(novelInfo.value.content);
  return truncateText(text);
});

// 查看完整简介
const showFullSummary = ():void => {
  ElMessageBox.alert(htmlToText(novelInfo.value.content), '作品简介', {
    confirmButtonText: '关闭',
    customClass: 'summary-dialog',
    dangerouslyUseHTMLString: false
  });
};

// 获取小说详情
const getNovelDetail = async ():Promise <void> => {
  try {
    loading.value = true;
    const res = await artGetDetailService(novelId) as ApiResponse<NovelInfo>;
    if (res.data.code === '0000') {
      novelInfo.value = res.data.data;
    } else {
      ElMessage.error(res.data.msg || '获取小说详情失败');
    }
  } catch (error) {
    ElMessage.error('获取小说详情失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 获取章节列表
const getChapters = async ():Promise <void> => {
  try {
    const res = await getChapterList({ novelId }) as ApiResponse<ChapterListResponse>;
    if (res.data.code === '0000') {
      chapterList.value = res.data.data.list || [];
    } else {
      ElMessage.error(res.data.msg || '获取章节列表失败');
    }
  } catch (error) {
    ElMessage.error('获取章节列表失败');
    console.error(error);
  }
};

// 添加章节
const openAddChapter = ():void => {
  isEditing.value = false;
  chapterForm.value = {
    novelId,
    title: '',
    chapterNum: chapterList.value.length + 1,
    status: '草稿',
    content: '',
    pub_date: ''
  };
  
  chapterDialogVisible.value = true;
  
  // 延迟设置编辑器内容
  nextTick(() => {
    if (quillEditorRef.value) {
      quillEditorRef.value.setHTML('');
    }
  });
};

// 编辑章节
const openEditChapter = (chapter):void => {
  isEditing.value = true;
  chapterForm.value = { ...chapter };
  
  chapterDialogVisible.value = true;
  
  // 延迟设置编辑器内容
  nextTick(() => {
    if (quillEditorRef.value && chapterForm.value.content) {
      quillEditorRef.value.setHTML(chapterForm.value.content);
    }
  });
};

// 保存章节
const saveChapter = async ():Promise <void> => {
  try {
    if (!chapterForm.value.title?.trim()) {
      ElMessage.error('请输入章节标题');
      return;
    }

    let res;
    if (isEditing.value) {
      res = await editChapter(chapterForm.value) as ApiResponse;
    } else {
      res = await addChapter(chapterForm.value) as ApiResponse;
    }
    
    if (res.data.code === '0000') {
      ElMessage.success(isEditing.value ? '章节编辑成功' : '章节添加成功');
      chapterDialogVisible.value = false;
      getChapters();
    } else {
      ElMessage.error(res.data.msg || '操作失败');
    }
  } catch (error) {
    ElMessage.error(isEditing.value ? '编辑章节失败' : '添加章节失败');
    console.error(error);
  }
};

// 删除章节
const handleDeleteChapter = async (chapter):Promise <void> => {
  try {
    await ElMessageBox.confirm(
      `确定删除章节"${chapter.title}"吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    const res = await deleteChapter({ id: chapter.id }) as ApiResponse;
    if (res.data.code === '0000') {
      ElMessage.success('章节删除成功');
      getChapters();
    } else {
      ElMessage.error(res.data.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除章节失败');
    }
  }
};

// 格式化日期
const formatDate = (dateString:string | undefined):string => {
  if (!dateString) return '-';
  return new Date(dateString).toLocaleDateString('zh-CN');
};

// 状态标签类型
const statusTagType = (status):string => {
  return status === '发布' ? 'success' : 'info';
};

// 关闭对话框时的清理
const handleDialogClose = ():void => {
  chapterDialogVisible.value = false;
};

// 初始化
onMounted(() => {
  getNovelDetail();
  getChapters();
});
</script>

<template>
  <page-container title="小说详情">
    <template #extra>
      <el-button type="primary" :icon="Plus" @click="openAddChapter">添加章节</el-button>
    </template>
    
    <div class="novel-detail-container" v-loading="loading">
      <!-- 基本信息卡片 -->
      <el-card class="novel-info-card" shadow="hover">
        <div class="novel-info">
          <!-- 封面区域 -->
          <div class="novel-cover">
            <el-image 
              :src="novelInfo.cover" 
              :alt="novelInfo.title"
              fit="cover"
              class="cover-image"
            >
              <template #error>
                <div class="cover-error">
                  <el-icon><Picture /></el-icon>
                  <span>暂无封面</span>
                </div>
              </template>
            </el-image>
          </div>
          
          <!-- 元信息区域 -->
          <div class="novel-meta">
            <h2 class="novel-title">{{ novelInfo.title || '加载中...' }}</h2>
            
            <div class="meta-grid">
              <div class="meta-item">
                <span class="label">分类：</span>
                <span class="value">{{ novelInfo.cate_name || '-' }}</span>
              </div>
              
              <div class="meta-item">
                <span class="label">状态：</span>
                <el-tag :type="statusTagType(novelInfo.state)" size="small">
                  {{ novelInfo.state || '-' }}
                </el-tag>
              </div>
              
              <div class="meta-item">
                <span class="label">发布时间：</span>
                <span class="value">{{ formatDate(novelInfo.pub_date) }}</span>
              </div>
              
              <div class="meta-item">
                <span class="label">章节数：</span>
                <span class="value">{{ chapterList.length }} 章</span>
              </div>
            </div>
            
            <!-- 简介区域 -->
            <div class="summary-section">
              <div class="summary-header">
                <span class="label">简介：</span>
                <el-button 
                  v-if="novelInfo.content && htmlToText(novelInfo.content).length > 120" 
                  type="text" 
                  size="small" 
                  @click="showFullSummary"
                >
                  查看完整
                </el-button>
              </div>
              <p class="novel-summary">
                {{ plainSummary || '暂无简介' }}
              </p>
            </div>
          </div>
        </div>
      </el-card>
      
      <!-- 章节列表卡片 -->
      <el-card class="chapter-list-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>章节列表</span>
            <span class="chapter-count">共 {{ chapterList.length }} 章</span>
          </div>
        </template>
        
        <div class="chapter-scroll-container">
          <div 
            v-for="chapter in chapterList" 
            :key="chapter.id" 
            class="chapter-item"
          >
            <div class="chapter-info">
              <span class="chapter-num">第{{ chapter.chapterNum }}章</span>
              <span class="chapter-title">{{ chapter.title }}</span>
              <el-tag 
                :type="statusTagType(chapter.status)" 
                size="small"
                class="status-tag"
              >
                {{ chapter.status }}
              </el-tag>
            </div>
            
            <div class="chapter-actions">
              <span class="chapter-date">{{ formatDate(chapter.pub_date) }}</span>
              <el-button 
                type="primary" 
                size="small" 
                :icon="Edit" 
                @click="openEditChapter(chapter)"
              >
                编辑
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                :icon="Delete" 
                @click="handleDeleteChapter(chapter)"
              >
                删除
              </el-button>
            </div>
          </div>
          
          <div v-if="chapterList.length === 0" class="empty-chapters">
            <el-empty description="暂无章节" :image-size="80" />
            <el-button type="primary" @click="openAddChapter" style="margin-top: 16px;">
              添加第一章
            </el-button>
          </div>
        </div>
      </el-card>
      
      <!-- 添加/编辑章节对话框 -->
      <el-dialog 
        :title="isEditing ? '编辑章节' : '添加章节'" 
        v-model="chapterDialogVisible"
        width="90%"
        :before-close="handleDialogClose"
        top="5vh"
        class="chapter-editor-dialog"
      >
        <el-form :model="chapterForm" label-width="80px">
          <el-form-item label="章节号" required>
            <el-input-number 
              v-model="chapterForm.chapterNum" 
              :min="1" 
              :max="999"
              controls-position="right"
            />
          </el-form-item>
          
          <el-form-item label="章节标题" required>
            <el-input 
              v-model="chapterForm.title" 
              placeholder="请输入章节标题" 
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
          
          <el-form-item label="状态">
            <el-radio-group v-model="chapterForm.status">
              <el-radio label="发布">发布</el-radio>
              <el-radio label="草稿">草稿</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="章节内容" class="editor-form-item">
            <div class="quill-editor-container">
              <QuillEditor
                ref="quillEditorRef"
                v-model:content="chapterForm.content"
                content-type="html"
                :options="editorOptions"
                class="quill-editor"
              />
            </div>
          </el-form-item>
        </el-form>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleDialogClose">取消</el-button>
            <el-button type="primary" @click="saveChapter">保存</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </page-container>
</template>

<style scoped>
.novel-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.novel-info-card {
  margin-bottom: 20px;
}

.novel-info {
  display: flex;
  gap: 24px;
  align-items: flex-start;
}

.novel-cover {
  flex-shrink: 0;
}

.cover-image {
  width: 160px;
  height: 220px;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.cover-error {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;
  border-radius: 6px;
}

.novel-meta {
  flex: 1;
  min-width: 0;
}

.novel-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  line-height: 1.3;
}

.meta-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
  margin-bottom: 20px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.meta-item .label {
  color: #6b7280;
  font-weight: 500;
  min-width: 60px;
}

.meta-item .value {
  color: #374151;
  font-weight: 500;
}

.summary-section {
  border-top: 1px solid #e5e7eb;
  padding-top: 16px;
}

.summary-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.novel-summary {
  margin: 0;
  line-height: 1.6;
  color: #4b5563;
  font-size: 14px;
  white-space: pre-wrap;
}

.chapter-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chapter-count {
  color: #6b7280;
  font-size: 14px;
}

.chapter-scroll-container {
  max-height: 500px;
  overflow-y: auto;
  padding-right: 8px;
}

.chapter-scroll-container::-webkit-scrollbar {
  width: 6px;
}

.chapter-scroll-container::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

.chapter-scroll-container::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.chapter-scroll-container::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

.chapter-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f1f5f9;
  transition: background-color 0.2s;
}

.chapter-item:hover {
  background-color: #f8fafc;
  border-radius: 6px;
}

.chapter-item:last-child {
  border-bottom: none;
}

.chapter-info {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
  min-width: 0;
}

.chapter-num {
  color: #6b7280;
  font-size: 14px;
  min-width: 60px;
}

.chapter-title {
  color: #1f2937;
  font-weight: 500;
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.status-tag {
  margin-left: auto;
}

.chapter-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.chapter-date {
  color: #9ca3af;
  font-size: 12px;
  min-width: 80px;
  text-align: right;
}

.empty-chapters {
  padding: 40px 20px;
  text-align: center;
  color: #6b7280;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* Vue Quill 编辑器样式 */
.quill-editor-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.quill-editor {
  min-height: 400px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .novel-detail-container {
    padding: 16px;
  }
  
  .novel-info {
    flex-direction: column;
    gap: 16px;
  }
  
  .novel-cover {
    align-self: center;
  }
  
  .cover-image {
    width: 140px;
    height: 200px;
  }
  
  .meta-grid {
    grid-template-columns: 1fr;
    gap: 8px;
  }
  
  .chapter-item {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .chapter-info {
    justify-content: space-between;
  }
  
  .chapter-actions {
    justify-content: flex-end;
  }
  
  .chapter-title {
    white-space: normal;
  }
}

@media (max-width: 480px) {
  .novel-detail-container {
    padding: 12px;
  }
  
  .chapter-info {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .chapter-actions {
    flex-wrap: wrap;
    justify-content: space-between;
  }
  
  .chapter-date {
    min-width: auto;
  }
}
</style>

<style>
/* 全局样式用于简介对话框 */
.summary-dialog .el-message-box__message {
  white-space: pre-wrap;
  line-height: 1.6;
  max-height: 60vh;
  overflow-y: auto;
  padding: 8px 0;
}

/* Vue Quill 编辑器对话框样式 */
.chapter-editor-dialog .el-dialog {
  max-width: 1200px;
}

.chapter-editor-dialog .el-dialog__body {
  padding-top: 20px;
  padding-bottom: 20px;
}

/* Vue Quill 自定义样式 */
.ql-editor {
  min-height: 400px;
  font-size: 14px;
  line-height: 1.6;
}

.ql-toolbar {
  border-bottom: 1px solid #e4e7ed;
}

.ql-container {
  border-top: none;
}
</style>